<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-card>
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="车位编号">
              <el-input v-model="formInline.code"></el-input>
            </el-form-item>
            <el-form-item label="停车场编号">
              <el-input v-model="formInline.lotCode"></el-input>
            </el-form-item>
            <el-form-item label="是否可用">
              <el-select v-model="formInline.isAvailable" placeholder="请选择">
                <el-option label="全部" value=""></el-option>
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="预定用户ID">
              <el-input v-model="formInline.userId"></el-input>
            </el-form-item>
            <el-form-item label="是否会员专属">
              <el-select v-model="formInline.isMemberOnly" placeholder="请选择">
                <el-option label="全部" value=""></el-option>
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="fetchData">查询</el-button>
              <el-button type="info" @click="resetQueryData">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card v-loading="isLoading" element-loading-text="加载中...">
          <el-form-item style="float: right;">
              <el-button type="success" @click="showAddDialog = true">新增</el-button>
              <el-button type="warning" @click="handleBatchDelete" >批量删除</el-button>
              <el-button type="danger" @click="deleteAll" >清空数据</el-button>
            </el-form-item>
          <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="序号" width="70" align="center" style = "background-color :black">
              <template #default="scope">
                <div class="serial-number">
                  {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="id" label="车位id" v-if="false"></el-table-column>
            <el-table-column prop="lotCode" label="停车场编号" width="300"></el-table-column>
            <el-table-column prop="code" label="车位编号" width="300"></el-table-column>
            <el-table-column prop="isAvailable" label="是否可用" width="300">
              <template #default="scope">
                <span>{{ scope.row.isAvailable === 1 ? '是' : '否' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="isMemberOnly" label="是否会员专属" width="300">
              <template #default="scope">
                <span>{{ scope.row.isMemberOnly === 1 ? '是' : '否' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="userId" label="预定用户ID" width="180"></el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.row)">修改</el-button>
                <el-button size="small" type="danger" @click="handleDelete([scope.row.id])">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 20px; margin-bottom: 20px; text-align: right; float: right;">
            <el-config-provider :locale="locale">
              <el-pagination
                background
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                :current-page="currentPage"
                :page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              ></el-pagination>
            </el-config-provider>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <AddSpaceDialog 
      :visible="showAddDialog" 
      @update:visible="showAddDialog = $event"
      @add="handleAdd"
    />
    <EditSpaceDialog 
      :visible="showEditDialog" 
      :parkingSpaceId="updateSpaceId"
      :updateLotCode="updateLotCode"
      :updateIsAvailable="updateIsAvailable"
      :updateUserId="updateUserId"
      :updateIsMemberOnly="updateIsMemberOnly"
      :updateCode="updateCode"
      @update:visible="showEditDialog = $event"
      @edit="fetchData"
    />
  </div>
</template>
<script setup>
import zhCn from 'element-plus/es/locale/lang/zh-cn'; 
import { ref, watch } from 'vue';
import axios from 'axios';
import AddSpaceDialog from '@/components/AddSpaceDialog.vue';
import EditSpaceDialog from '@/components/EditSpaceDialog.vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';

const route = useRoute();
const showAddDialog = ref(false);
const showEditDialog = ref(false);
const updateSpaceId = ref(0);
const updateLotCode = ref('');
const updateIsAvailable= ref('');
const updateUserId= ref('');
const updateIsMemberOnly= ref('');
const updateCode= ref('');

const formInline = ref({
  id: '',
  lotCode: '',
  isAvailable: '',
  userId: '',
  isMemberOnly: '',
  code: ''
});
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const locale = zhCn;
const isLoading = ref(false);
const selectedIds = ref([]);

const api = axios.create({
    baseURL:'http://localhost:8092',
    headers: {
        'Authorization': `${localStorage.getItem('token')}`
    }
})
watch(() => route.path, (newPath) => {
  if(newPath === '/admin/SpaceManagement') {
    console.error("刷新SpaceManagement");
    fetchData();
  }
});
// 获取数据函数
const fetchData = async () => {
  isLoading.value = true;
  const params = {
      ...formInline.value,
      pageIndex: currentPage.value,
      pageSize: pageSize.value
    };
  Object.keys(params).forEach(key => (params[key] === '' || params[key] === null) && delete params[key]);
  // 如果 'code' 存在且有值，则替换为 'parkingSpaceCode'
  if ('code' in params && params.code) {
    params.parkingSpaceCode = params.code;
    delete params.code;
  }
  try {
    const response = await api.get('/api/v1/parking-space/parking-space-info', { params });
      if (response.data.code === "200") {
        if(response.data.data != null){
          tableData.value = response.data.data.records;
          total.value = response.data.data.total;
        } else {
          tableData.value = [];
          total.value = 0;
        }
      } else {
        ElMessage({
          title: '错误',
          message: '获取停车位记录失败！' + response.data.message,
          type: 'error',
          showClose: false
        });
      }
  } catch (error) {
    ElMessage({
      title: '错误',
      message: '获取停车位记录失败！' + error.message,
      type: 'error',
      showClose: false
    });
  } finally {
    isLoading.value = false;
  }
};

// 新增按钮点击事件处理
const handleAdd = async () => {
  await fetchData();
};
// 编辑和删除事件处理保持不变
const handleEdit = async (row) => {
  updateSpaceId.value = row.id;
  updateLotCode.value = row.lotCode;
  updateIsAvailable.value = row.isAvailable;
  updateUserId.value = row.userId;
  updateIsMemberOnly.value = row.isMemberOnly;
  updateCode.value = row.code;
  showEditDialog.value = true;
};
const handleDelete = async (ids) => {
  try {
    const response = await api.delete('/api/v1/parking-space/parking-space-info', {
       data: { ids }
    });
    if (response.data.code === "200") {
      ElMessage({
        title: '成功',
        message: '删除成功',
        type: 'success',
        showClose: false
      });
      // 清空已选择的ID列表
      selectedIds.value = [];
    } else {
      ElMessage({
        title: '错误',
        message: '删除失败！' + response.data.message,
        type: 'error',
        showClose: false
      });
    }
  } catch (error) {
    ElMessage({
      title: '错误',
      message: '删除失败！' + error.message,
      type: 'error',
      showClose: false
    });
  } finally {
    await fetchData();
    isLoading.value = false;
  }
};
const handleBatchDelete = async () => {
  handleDelete(selectedIds.value);
}
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id);
};
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchData();
};
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchData();
};
const deleteAll = async () => {
  ElMessageBox.confirm(
    '此操作将永久删除所有数据, 是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    isLoading.value = true; // 开始加载
    try {
      // 发送删除请求到后端
      const response = await api.delete('/api/v1/parking-space/all-parking-space-info');
      if (response.data.code === "200") {
        ElMessage({
          title: '成功',
          message: '所有数据删除成功',
          type: 'success',
          showClose: false,
        });
        // 清空前端 tableData
        tableData.value = [];
      } else {
        ElMessage({
          title: '错误',
          message: '删除失败！' + response.data.message,
          type: 'error',
        });
      }
    } catch (error) {
      ElMessage({
        title: '错误',
        message: '删除失败！' + error.message,
        type: 'error',
      });
    } finally {
      isLoading.value = false;
      fetchData();
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    });
  });
}
const resetQueryData = () =>{
  formInline.value = {
    id: '',
    lotCode: '',
    isAvailable: '',
    userId: '',
    isMemberOnly: '',
    code: ''
  };
  fetchData();
}

fetchData();
</script>

<style scoped>
.admin-dashboard {
  height: 100vh;
}
.el-container {
  height: 100%;
}
.el-aside {
  background-color: #f8f9fa;
}
.el-main {
  padding: 20px;
}
.el-card {
  margin-bottom: 20px;
}
.el-table .cell {
  pointer-events: none;
}
.el-select {
  width: 180px;
}
.pagination {
  margin: 2rem auto;
  display: flex;
  justify-content: center;
}
</style>